<!--
* description: 采购管理-备件订单制作_总部
* author: zouzhu
* createdDate: 2021-01-22
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :callback-obj="callbackObj"
    />
    <ModificationEdit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible.sync="editPopupsVisible"
      :popups-state="editPopupsState"
    />
  </div>
</template>

<script>
// import { mapActions, mapGetters, mapMutations } from 'vuex'
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/pa/procuremenData'
import ModificationEdit from './modificationEdit'
import Vue from 'vue'

export default {
  name: 'PartOrderHQMake',
  components: {
    OneTableTemplate,
    ModificationEdit
  },

  mixins: [oneTableWithViewTemplateMixins],

  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next(vm => { vm.queryTable(1) })
    })
  },
  data() {
    return {
      selectData: [],
      editRowData: {},
      editPopupsVisible: false,

      apiConfig: api.sparePartsOrderQueryHQ,

      tableButtons: [
        {
          conmpKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          text: '查询',
          clickEvent: () => this.queryTable(1),
          position: 'right'
        },
        {
          conmpKey: 'btnKey2',
          size: 'small',
          name: 'add',
          clickEvent: () => {
            // 新增
            this.showEdit('add')
          },
          text: this.$t('sys.button.add'),
          position: 'left'
        },
        {
          conmpKey: 'btnKey3',
          size: 'small',
          name: 'confirm',
          text: '提交',
          clickEvent: () => this.submit(),
          position: 'right'
        },
        {
          conmpKey: 'btnKey4',
          size: 'small',
          name: 'cancel',
          text: '作废',
          disabled: true,
          clickEvent: () => this.invalid(),
          position: 'left'
        },
        {
          compKey: 'btnKey5',
          size: 'small',
          name: 'export',
          clickEvent: () => this.exportExcel(),
          text: this.$t('sys.button.export'),
          position: 'left'
        },
        {
          conmpKey: 'btnKey6',
          size: 'small',
          name: 'reset',
          text: '重置',
          clickEvent: () => this.reset(),
          position: 'right'
        }
        // {
        //   compKey: 'btnKey7',
        //   size: 'small',
        //   name: 'importTemplate',
        //   icon: 'iconfont icon-importTemplate',
        //   clickEvent: () => this.handFileListChange(),
        //   text: '导入',
        //   position: 'upload'
        // },
        // {
        //   compKey: 'btnKey8',
        //   type: 'text',
        //   size: 'small',
        //   name: 'importTemplateDownload',
        //   icon: 'iconfont  icon-importTemplateDownload',
        //   click: () => this.templateDownload(),
        //   text: 'Excel导入模板下载',
        //   position: 'left'
        // }
      ],
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '网点编码：',
              codeField: 'dlrCode',
              component: () => import('@/components/ve/multipleSearchInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              dataToObject: {
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '网点编码：',
                    codeField: 'dlrCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '网点名称：',
                    codeField: 'dlrShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'dlrCode',
                    label: '网点编码'
                  },
                  {
                    prop: 'dlrShortName',
                    label: '网点名称'
                  }
                ],
                formField: {
                  dlrCode: '',
                  dlrShortName: ''
                },
                oFields: 'dlrCode,dlrShortName',
                returnField: {
                  prop: 'dlrCode',
                  label: '网点编码'
                },
                api: api.findDlrList
              }
            },
            {
              compKey: 'compKey2',
              labelName: '订单号：',
              codeField: 'purOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '订货日期：',
              codeField: 'orderStartTime,orderEndTime',
              component: () =>
                import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '订单类型：',
              codeField: 'orderTypeCode',
              oFields: 'orderTypeCode,orderTypeName',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: api.findOrderTypeList
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '订单状态：',
              codeField: 'orderStatusCode',
              oFields: 'orderStatusCode,orderStatusName',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: api.findOrderStatusList
              },
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey6',
              labelName: '运输方式：',
              codeField: 'transportModeID',
              textField: 'transportModeName',
              oFields: 'transportModeId,transportModeName',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: {
                  ServiceCode: 'queryPartTransports',
                  APIUrl:
                      '/mp/e3sh/spareparts/mallorder/partSaleOrderQueryOemService/queryPartTransports.do'
                }
              },
              type: 'dropdownList',
              isMul: false,
              isMust: false
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'purchaseOrderID',
              label: '订单D',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlID',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'transportModeID',
              label: '运输方式ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'isEnable',
              label: '是否启用',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn',
              label: '操作',
              codeField: 'controlBtn',
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '修改',
                  codeField: 'editControlBtn',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: index => {
                    this.editRowData = this.$utils.deepCopy(
                      this.$refs['multipleTable'].list[index]
                    )
                    this.showEdit('edit')
                  }
                }
              ]
            },
            {
              prop: 'purOrderCode',
              label: '订单号',
              width: 140
            },
            {
              prop: 'purOrderTypeCn',
              label: '订单类型'
            },
            {
              prop: 'dlrCode',
              label: '网点编码'
            },
            {
              prop: 'dlrShortName',
              label: '网点名称'
            },
            {
              prop: 'purDate',
              label: '订货日期',
              width: 140
            },
            {
              prop: 'orderVariety',
              label: '订货品种数'
            },
            {
              prop: 'purAmount',
              label: '订货金额'
            },
            // {
            //   prop: 'transportModeName',
            //   label: '运输方式 '
            // },
            {
              prop: 'orderStatus',
              label: '审核状态'
            },
            {
              prop: 'createdDate',
              label: '制单时间',
              width: 140
            },
            {
              prop: 'creator',
              label: '制单人'
            },
            {
              prop: 'oemAuditor',
              label: '总部审核人'
            },
            {
              prop: 'rejectReason',
              label: '驳回原因',
              width: 140
            },
            {
              prop: 'remark',
              label: '备注'
            }
          ],
      formField: this.$utils.getFormField(this, {
        orderTypeCode: '',
        orderStatusCode: '',
        dlrCode: '',
        purOrderCode: '',
        orderStartTime: '',
        orderEndTime: '',
        purOrderType: '',
        // orderStatus: '',
        transportModeName: '',
        transportModeID: '',
        updateControlID: ''
      }),

      // 单表格模版页面组件回调事件
      callbackObj: {
        onCheckSelectChange: selection => {
          this.selectData = selection

          this.handleSelectionChange(selection)
        }
      }
    }
  },
  watch: {
    // '$route': {
    //   handler(route) {
    //     if (route.name === 'partOrderHQMake') {
    //       this.queryTable()
    //     }
    //   },
    //   immediate: true
    // }
  },
  mounted() {
  },
  methods: {
    // 提交
    submit() {
      if (!this.selectData.length) {
        return this.$message('至少选择一条数据')
      }
      this.$confirm('确定要提交吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          const queryObj = {
            // 保存需要传 type="mutation"
            type: 'mutation',
            apiConfig: {
              APIUrl:
                '/mp/e3sh/spareparts/sparePartsOrderMakingService/submitOrderInfo.do'
            },
            // 条件/实体参数（变量），根据typeParam中的定义配置
            variables: {
              list: this.selectData.reduce((pre, cur, idx) => {
                const { purchaseOrderId, updateControlId } = cur
                pre.push({ purchaseOrderId, updateControlId })
                return pre
              }, [])
            }
          }
          // 转换了中台请求格式数据
          var paramD = this.$getParams(queryObj)
          this.$requestAPI(paramD).then(response => {
            if (response.result === 1) {
              this.$message({
                message: response.msg
              })
            } else {
              this.$message({
                message: response.msg
              })
            }
            this.queryTable(1)
          })
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 作废
    async invalid() {
      const res = await this.$confirm('确定要作废吗?', '提示')
      if (res !== 'confirm') return
      const queryObj = {
        // 保存需要传 type="mutation"
        type: 'mutation',
        apiConfig: { APIUrl: '/mp/e3sh/spareparts/sparePartsOrderMakingService/cancellationOrderInfo.do' },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          list: this.selectData.reduce((pre, cur, idx) => {
            const { purchaseOrderId, updateControlId } = cur
            pre.push({ purchaseOrderId, updateControlId })
            return pre
          }, [])
        }
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({ message: response.msg })
          this.selectData = []
        } else {
          this.$message({
            message: response.msg
          })
        }
        this.queryTable(1)
      })
    },

    // // 导入
    // handFileListChange(file, fileList) {
    //   if (this.beforeAvatarUpload(file)) {
    //     this.handleChange(file)
    //   }
    // },
    // beforeAvatarUpload(file) {
    //   if (file.size > 50 * 1024 * 1024) {
    //     this.$message({
    //       message: '文件大小不能超过50M',
    //       type: 'warning'
    //     })
    //     return false
    //   }
    //   const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
    //   if (fileType !== 'xls' && fileType !== 'xlsx') {
    //     this.$message({
    //       message: '只能导入后缀为xls,xlsx的文件！',
    //       type: 'warning'
    //     })
    //     return false
    //   }
    //   return true
    // },
    // handleChange(param) {
    //   const loading = this.$loading({
    //     lock: true,
    //     text: '导入中...',
    //     spinner: 'el-icon-loading',
    //     background: 'rgba(0, 0, 0, 0.7)'
    //   })
    //   const that = this
    //   const url = api.creditBeachImport.APIUrl
    //   that.$requestUpload(url, param).then(response => {
    //     loading.close()
    //     if (response.result === '1') {
    //       this.$message({
    //         message: '导入成功',
    //         type: 'success'
    //       })
    //       that.queryTable(1)
    //     } else {
    //       this.$message({
    //         message: response.msg,
    //         type: 'warning'
    //       })
    //     }
    //   }).catch(_ => {})
    // },

    // // 模板下载
    // templateDownload() {
    //   this.$requestAPI({
    //     variables: { dataType: 'excel' },
    //     apiUrl: api.creditDownloadTemplate.APIUrl
    //   }).then(res => {
    //     this.$utils.downloadFile(res, 'excel导入模板下载.xlsx')
    //   })
    // }

    // 导出
    exportExcel() {
      const fileName = this.$utils.fileNameWithTime('备件订单制作_总部.xlsx')
      this.$requestAPI({
        apiUrl: api.importSparePartsOrderHQ.APIUrl,
        variables: { dataType: 'excel' }
      })
        .then(res => {
          this.$utils.downloadFile(res, fileName)
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach(item => {
          item.disabled = !isCheck
        })
      }
    }
  }
}
</script>
